package com.lhg.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhg.utils.dto.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class AiRecognizeUtil {
//    @Value("${api.bluelm.app-id}")
//    private String appId;
//
//    @Value("${api.bluelm.secret}")
//    private String appKey;

    public String vivogpt(String prompt, String questionHeader) throws Exception {
        String appId = "3034428160";
        String appKey = "NGMHEfELwCmzCcYH";
        String URI = "/vivogpt/completions";
        String DOMAIN = "api-ai.vivo.com.cn";
        String METHOD = "POST";
        UUID requestId = UUID.randomUUID();
        System.out.println("requestId: " + requestId);


        Map<String, Object> map = new HashMap<>();
        map.put("requestId", requestId.toString());
        String queryStr = mapToQueryString(map);

        //构建请求体
        Map<String, String> data = new HashMap<>();
        data.put("prompt", questionHeader+prompt);
        data.put("model", "vivo-BlueLM-TB");
        UUID sessionId = UUID.randomUUID();
        data.put("sessionId", sessionId.toString());
        System.out.println(sessionId);


        HttpHeaders headers = VivoAuthUtil.generateAuthHeaders(appId, appKey, METHOD, URI, queryStr);
        headers.add("Content-Type", "application/json");
        System.out.println(headers);
        String url = String.format("http://%s%s?%s", DOMAIN, URI, queryStr);
        String requsetBodyString = new ObjectMapper().writeValueAsString(data);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        httpHeaders.addAll(headers);
        HttpEntity<String> requestEntity = new HttpEntity<>(requsetBodyString, httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("Response body: " + response.getBody());
        } else {
            System.out.println("Error response: " + response.getStatusCode());
        }
        return response.getBody();
    }

    public static String mapToQueryString(Map<String, Object> map) {
        if (map.isEmpty()) {
            return "";
        }
        StringBuilder queryStringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (queryStringBuilder.length() > 0) {
                queryStringBuilder.append("&");
            }
            queryStringBuilder.append(entry.getKey());
            queryStringBuilder.append("=");
            queryStringBuilder.append(entry.getValue());
        }
        return queryStringBuilder.toString();
    }
//    private final WebClient webClient;
//    private final SignatureUtil signatureUtil;
//
//    @Autowired
//    public AiRecognizeUtil(WebClient webClient, SignatureUtil signatureUtil) {
//        this.webClient = webClient;
//        this.signatureUtil = signatureUtil;
//    }
//
//
//    public Mono<ResponseEntity<String>> sendMessage(ChatMessage message) {
//        Map<String, String> queryParams = new HashMap<>();
//        queryParams.put("requestId", UUID.randomUUID().toString());  // 生成唯一的requestId
//        //queryParams.put("requestId", "1e344557-8e8b-43e3-a36e-94e7f36616e0");
//        // 创建一个MultiValueMap来存储转换后的参数
//        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
//        queryParams.forEach((key, value) -> multiValueMap.add(key, value));
//
//        return webClient.post()
//                .uri(uriBuilder -> uriBuilder.path("/vivogpt/completions")
//                        .queryParams(multiValueMap)  // 使用MultiValueMap作为查询参数
//                        .build())
//                .headers(headers -> headers.setAll(signatureUtil.generateAuthHeaders("POST", "/vivogpt/completions", queryParams)))
//                .bodyValue(buildRequestBody(message))
//                .retrieve()
//                .bodyToMono(String.class)
//                .map(body -> ResponseEntity.ok().body(body))
//                .onErrorResume(e -> {
//                    e.printStackTrace();  // 在实际部署中应考虑更合适的错误处理方式
//                    return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error processing your request: " + e.getMessage()));
//                });
//    }
//
//    // 确保当构建JSON字符串时包括sessionId
//    private String buildRequestBody(ChatMessage message) {
//        return String.format("{\"prompt\": \"%s\", \"model\": \"vivo-BlueLM-TB\", \"sessionId\": \"%s\"}",
//                message.getContent(),
//                message.getSessionId()); // 使用传递的sessionId
//    }
}
